package Demo.ClassPath;

import Demo.ClassPath.Impl.StarRead;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ClassPath {
    private Read bootstrapClasspath;
    private Read extensionClasspath;
    private Read userClasspath;
    public ClassPath(String jreOption,String userOption){
        bootstrapAndExtension(jreOption);
        parseUserClasspath(userOption);
    }
    private void bootstrapAndExtension(String jreOption){
        String jreDir = getjreDir(jreOption);
        String jreLibPath = Paths.get(jreDir,"lib")+ File.separator+"*";
        bootstrapClasspath = new StarRead(jreLibPath);
        String jreExtPath = Paths.get(jreDir,"lib","ext")+File.separator+"*";
        extensionClasspath = new StarRead(jreExtPath);
    }
    private String getjreDir(String jreOption) {
        if (jreOption != null && Files.exists(Paths.get(jreOption))) {
            return jreOption;//如果存在该路径则返回
        }
        if (Files.exists(Paths.get("./jre"))) {
            return "./jre";//否则查看项目文件下是否有该文件夹
        }
        String jh = System.getenv("JAVA_HOME");
        if (jh != null) {
            return Paths.get(jh, "jre").toString();//直接搜环境变量，查看是否有该目录
        }
        throw new RuntimeException("Can not find JRE folder!");
    }
    private void parseUserClasspath(String cpOption) {
        if (cpOption == null) {
            cpOption = ".";
        }
        userClasspath = Read.create(cpOption);
    }
    public byte[] readClass(String className) throws IOException {
        className = className + ".class";
        try {
            return bootstrapClasspath.readClass(className);
        }catch (IOException e){
            // 可能是正常现象
        }
        try {
            return extensionClasspath.readClass(className);
        }catch (IOException e){}
        return userClasspath.readClass(className);
    }
}
